package com.teckteam.ptvsystem.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import com.teckteam.ptvsystem.controller.CancelWindowListener;
import com.teckteam.ptvsystem.controller.ScrapeFailedException;
import com.teckteam.ptvsystem.model.ScraperHelper;

/**
 * Dialog prompt for handling geocoding auto-filling using an internet service,
 *
 */
public class GeocodePrompt extends JDialog implements Observer
{
   private JourneyPlanner jpDialog;
   private JourneyChoicePanel jcp;
   private JTextField searchBox;
   private JLabel note = new JLabel("Requires an internet connection.  Obtain your GPS coordinates using the Google Maps search.");
   private JButton
      okBtn = new JButton("Geocode Now"),
      cancelBtn = new JButton("Cancel");
   private JPanel 
      btnPanel = new JPanel(),
      centerPanel = new JPanel(new BorderLayout()),
      northPanel = new JPanel(new BorderLayout());
   
   private JScrollPane scrollPane = new JScrollPane();
   private JTable resultsTable;
   private ScraperHelper scraper = new ScraperHelper(this);
   
   public GeocodePrompt(JourneyPlanner jpDialog, JourneyChoicePanel jcp)
   {
      this.searchBox = new JTextField();
      this.jpDialog = jpDialog;
      this.jcp = jcp;
      
      setModal(true);
      setLocationRelativeTo(null);
      setTitle("Grab GPS coordinates");
      setLayout(new BorderLayout());
      setSize(300, 300);
      setResizable(false);
      
      okBtn.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            launchGeocoder();
         }
      });
      cancelBtn.addActionListener(new CancelWindowListener(this));
      
      note.setPreferredSize(new Dimension(50, 30));
      btnPanel.add(okBtn);
      btnPanel.add(cancelBtn);
      
      searchBox.setPreferredSize(new Dimension(150, 25));
      scrollPane.getViewport().add(new JLabel("Results go here"));
      //centerPanel.add(scrollPane, BorderLayout.CENTER);
      //centerPanel.setBackground(Color.WHITE);
      //centerPanel.add(searchBox, BorderLayout.CENTER);
      
      searchBox.addKeyListener(new KeyAdapter()
      {
         public void keyPressed(KeyEvent e)
         {
            if(e.getKeyCode()==KeyEvent.VK_ENTER)
            {
               System.err.println("Enter key detecte4d");
               launchGeocoder();
            }
         }
      });
      
      northPanel.add(note, BorderLayout.NORTH);
      northPanel.add(searchBox, BorderLayout.CENTER);
      
      add(northPanel, BorderLayout.NORTH);
      add(scrollPane, BorderLayout.CENTER);
      add(btnPanel, BorderLayout.SOUTH);
      
      setVisible(true);
   }
   
   /**
    * Process search string to Google Maps and display geocoded results
    */
   public void launchGeocoder()
   {
      System.out.println("Enter Pressed");
      GeocodePrompt.this.invalidate();
      okBtn.setEnabled(false);
      searchBox.setEnabled(false);
      GeocodePrompt.this.validate();
      GeocodePrompt.this.repaint();
      scraper.launchGeocoder(searchBox.getText().replaceAll("[\\s]","+").replaceAll("[^a-zA-Z0-9-'+]",""));
   }
   
   protected void setGPSCoords(String lat, String lon, String name)
   {
      jcp.setGPSCoords(lat, lon, name);
      this.dispose();
   }
   
   /**
    * Executes when observed geocoding task thread has been completed.
    */
   public void update(Observable o, Object arg)
   {
      ArrayList<String[]> results;
      JPanel resultRows;
      
      this.invalidate();
      centerPanel.removeAll();
      scrollPane.getViewport().removeAll();
      //if((results = scraper.getGeocodeDetails())==null)
      if((results = (ArrayList<String[]>)arg)==null)
      {
         try
         {
            throw new ScrapeFailedException();
         } catch (ScrapeFailedException e) 
         {
            // handled
            return;
         }
      }
      
      //Populate scrollPane with GeocodeResultRowPanel instances
      resultRows = new JPanel(new GridLayout(results.size(), 1));
      this.invalidate();
      for(int i = 0; i < results.size(); i++)
         resultRows.add(new GeocodeResultRowPanel(results.get(i), this));
      
      
      scrollPane.getViewport().add(resultRows);
      //centerPanel.add(scrollPane, BorderLayout.CENTER);
      okBtn.setEnabled(true);
      searchBox.setEnabled(true);
      this.revalidate();
      this.repaint();
   }
}
